<template>
  <div>
    <div   style="width:80%; margin:0 auto">
      <div style="height:20px;"></div>
      <div style="display: flex">
        <div style=" line-height:30px; height:30px; border-left:5px solid #2caf2c; font-size:25px;
            font-weight:bold; padding-left:5px; margin:20px 20px">我的贴子</div>
      </div>
      <div style="height:3px; background-color:green; margin-bottom:10px"></div>
<!--  查询和新增贴子      -->
      <div class="card" style="margin-bottom: 13px;">
        <el-input clearable @clear="loadForum" style="width:240px; padding-right:5px" v-model="data.title"
                  :prefix-icon="Search" placeholder="请输入贴子标题查询"></el-input>
        <el-select v-model="data.viewData.categoryId" placeholder="请选择贴子分类" @clear="loadForum"
                   style="width: 240px">
          <el-option
              v-for="item in data.categoryData"
              :key="item.id"
              :label="item.title"
              :value="item.id"
          />
        </el-select>
        <el-button type="primary" @click="loadForum" style="margin-left: 10px">查 询</el-button>
        <el-button type="danger" @click="reset">重置查询</el-button>
        <el-button type="success" @click="handleAdd" style="">发布贴子</el-button>
      </div>
<!--  贴子布局      -->
      <div style="display: flex; grid-gap: 20px; background-color:#d8e3db; margin-top:5px;" v-for="item in data.viewData" :key="item">
        <!--     封面   -->
        <div style="flex: 1;">
          <img :src="item.img" alt="" @click="handleToForum('/front/forumdetail?id=' + item.id)" style="width:100%; height:200px; cursor: pointer"/>
        </div>
        <!--      内容  -->
        <div style="flex: 3; ">
<!--          贴子状态和贴主信息-->
          <div style="display:flex; ">
            <div style="font-size:20px; font-weight:bold; margin-bottom:3px; flex:4; cursor: pointer"
                 @click="handleToForum('/front/forumdetail?id=' + item.id)"
            >{{ item.title }}</div>
            <div style="flex:1; color:blue">
              <span>审核状态：</span>
              {{ item.status }}</div>
            <!--          编辑和删除-->
            <div>
              <el-button type="primary" @click="handleEdit(item)" style="">编辑</el-button>
              <el-button type="danger" icon="Delete" @click="del(item.id)" style=""></el-button>
            </div>
          </div>
          <div style="display: flex; color:#4ca34c">
            <span>贴子分类：</span>
            {{ item.categoryTitle }}</div>
          <div style="display:flex; margin-top:5px;">
            <img :src="item.userAvatar" alt=""  style="width:20px; height:20px; border-radius:50%;"/>
            <div style="margin-left:5px">
                <span class="clickable-text" @click="handleUserClick(item.userId)">
                  {{ item.userName }}
                </span>
            </div>
            <div style="margin-left:5px; font-size:10px; color:#988888">{{item.time}}</div>
          </div>


<!--          贴子内容-->
          <div class="line4" style="margin-top:5px; text-align: justify;">{{ item.description }}</div>
        </div>
      </div>

    </div>
<!--  新增表格    -->
    <el-dialog title="用户信息" v-model="data.formVisible" width="60%" destroy-on-close >
      <el-form ref="formRef" :model="data.forumData" :rules="data.rules" label-position="right" label-width="80px" padding="20px 30px 20px 0">
        <el-form-item prop="title" label="贴子标题">
          <el-input v-model="data.forumData.title" autocomplete="off" placeholder="请输入贴子标题"/>
        </el-form-item>
        <el-form-item prop="categoryId" label="贴子分类">
          <el-select
              v-model="data.forumData.categoryId"
              placeholder="请选择贴子分类"
              size="large"
              style="width: 240px"
          >
            <el-option
                v-for="item in data.categoryData"
                :key="item.id"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="image">
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{token: data.user.token}"
              list-type="picture"
              :on-success="handleFileSuccess">
            <el-button type="primary" >上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="content" label="贴子详情">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.forumData.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, reactive, ref, shallowRef} from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router/index.js";

const formRef = ref()

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  forumData: {},
  categoryData:[],
  title: null,
  categoryId: null,
  viewData: {},
  formVisible: false,
  rules:{
    title:[{required: true, message:"请输入贴子标题", trigger:"blur"},
      {min: 5,required: true, message:"标题最少五个字", trigger:"blur"}],
    content:[{required: true, message:"请输入贴子内容", trigger:"blur"}],
    categoryId:[{required: true, message:"请选择贴子分类", trigger:"blur"}],
  }
})

/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: data.user.token,
  },
  server: 'http://localhost:9999/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* wangEditor5 初始化结束 */

const loadForum = () => {
  request.get("/written/selectByRole",{
    params:{
      title: data.title,
      categoryId: data.viewData.categoryId,
    }
  }).then(res => {
    if (res.code === '200') {
      data.viewData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
loadForum()

const reset = () => {
  data.title = null;
  data.viewData.categoryId = null;
  loadForum()
}

const loadCategory = () => {
  request.get('/category/selectAll').then(res => {
    if (res.code === '200') {
      data.categoryData = res.data
    }else{
      ElMessage.error(res.msg)
    }
  })
}
loadCategory()

const handleUserClick = (row) => {
  const userId = String(row)
  router.push({path: `/front/otherperson/${userId}`})
}

const handleToForum = (url) => {
  setInterval(() => {
    location.href = url
  }, 500)
}

const handleAdd = () => {
  data.forumData = {};
  data.formVisible = true;
}

const handleEdit = (row) => {
  data.forumData = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

const handleFileSuccess = (res) => {
  data.forumData.img = res.data
}

const del = (id) => {
  ElMessageBox.confirm("删除后无法恢复，您确定要删除该贴子吗？", "删除确认窗口", {type: "warning"})
      .then(res => {
        request.delete(`/written/delete/${id}`).then(res => {
          if (res.code === '200') {
            ElMessage.success("删除成功")
            loadForum()
          }else{
            ElMessage.error(res.msg)
          }
        })
      }).catch(err => {})
}

const add = () => {
  request.post("/written/add", data.forumData).then(res => {
    if (res.code === '200') {
      ElMessage.success("发帖成功")
      data.formVisible = false;
      loadForum()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put("/written/update", data.forumData).then(res => {
    if (res.code === '200') {
      ElMessage.success("修改成功")
      data.formVisible = false;
      loadForum()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate(value => {
    if (value) {
      data.forumData.id ? update() : add()
    }
  })
}
</script>

<style scoped>
.card{
  background-color: #c9c9da;
}
.line4 {
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4; /*超出多少行省略*/
  overflow: hidden;
}

.clickable-text {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.clickable-text:hover {
  color: #3375b9;
}
</style>